import wx
from inspect import *
from pyeasyaccept.gui.ButtonCmdsPanel import ButtonCmdsPanel

class UserAppCmdsPanel(ButtonCmdsPanel):
    """
    It's a panel which contains commands of the user application
    Facade. Each button represents a command.
     
    @author: Danilo Torres
    """
        
    def __init__(self, parent, id, facadeInstance=None):
        """
        Initializes this panel.
        """
        ButtonCmdsPanel.__init__(self, parent, id)
        self.setFacadeInstance(facadeInstance)
                  
    def setFacadeInstance(self, userAppFacade):
        """
        Sets the user App facade instance.
        """
        self.RemoveAll()
        self.userAppFacade = userAppFacade
        self.loadUserAppCmds()
        self.setScrollBars()
        self.Layout()
        
    def loadUserAppCmds(self):
        """
        It gets each command of the user App Facade and put it in a button.
        """
        commandsStr = dir(self.userAppFacade)
        self.buttons = []
        for cmd in commandsStr:
            method = getattr(self.userAppFacade, cmd)
            if method != None and ismethod(method) and not cmd.startswith("__"):
                button = wx.Button(self, self.lastButtonID, cmd)
                doc = getdoc(method)
                if doc != None: button.SetToolTip(wx.ToolTip(doc))
                button.Bind(wx.EVT_BUTTON, self.buttonPressed)
                self.buttons.append(button)
                self.sizer.Add(button,(self.lastButtonID, 0), flag=wx.EXPAND)
                self.incrementLastButtonID()
                
    def RemoveAll(self):
        """
        Remove all the components of this panel.
        """
        children = self.GetChildren()
        for child in children:
            self.RemoveChild(child)
            child.Destroy()
        self.resetButtonID()
                
    def buttonPressed(self, event):
        """
        Event of button pressed. 
        """
        id = event.GetId()
        cmd = self.buttons.__getitem__(id).GetLabelText()
        method = self.getMethodFromCommand(cmd)
        args = self.getMethodArgs(method)
        
        for listener in self.listeners:
            listener.buttonPressed(cmd, args)
            
    def getMethodArgs(self, method):
        """
        Returns the arguments names of a given method.
        """        
        args = getargspec(method)[0]
        args.remove("self")
        return args
        
    def getMethodFromCommand(self, cmd):
        """
        Returns an instance of cmd. 
        """
        return getattr(self.userAppFacade, cmd)
    
    def reset(self):
        """
        Clears the UserAppCmdsPanel.
        """
        self.setFacadeInstance(None)
        self.Layout()